import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import {reqLogin, reqLogout, reqUserInfo} from "@/api/user";


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo:{
        routes:[],
        buttons:[],
        roles:[],
        name:"",
        avatar:""
    },
    menuRoutes: staticRoutes
  }),

	actions: {
    async login(username:string,password:string){
        try {
          const result = await reqLogin({username,password})
          setToken(result.token)
          this.token = result.token
        }catch (e){
            return Promise.reject(e)
        }
    },

    // getInfo () {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       this.userInfo.name = 'admin'
    //       this.userInfo.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    //       this.menuRoutes = staticRoutes
    //       resolve({name: this.name, avatar: this.avatar, token: this.token})
    //     }, 1000)
    //   })
    // },
    async getInfo(){
        try {
            const result = await reqUserInfo()
            this.userInfo = result
        }catch (e){
            return Promise.reject(e)
        }
    },
    async logout(){
        try {
            await reqLogout()
            this.reset()
        }catch (e){
            return Promise.reject(e)
        }
    },
    reset () {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userInfo = {
          routes:[],
          buttons:[],
          roles:[],
          name:"",
          avatar:""
      }
    },
	},
});
